
import { AlignRightOutlined, LeftOutlined, RedoOutlined, UndoOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import { Button, Card, Input, Layout, message, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';
import ReactQuill from 'react-quill';
const { Header, Content, Footer } = Layout;

import { EnumChapterStatus } from '@/models/constant';
import { getChapterByIdUsingGet, saveChapterUsingPost, switchChapterStatusUsingPost } from '@/services/novel-web/chapterController';
import { getNovelInfoUsingGet } from '@/services/novel-web/novelController';
import { MessageError } from '@/utils/commonUtils';
import './index.less';

const WriterModify: React.FC = () => {

  // url : /writer/modify-chapter/:novelId/:chapterId
  const { novelId, chapterId } = useParams<{ novelId: string, chapterId: string }>();
  const [novelInfo, setNovelInfo] = useState<API.NovelInfo>({});
  const [chapter, setChapter] = useState<API.Chapter>({});

  // const [loading,setLoading] =useState(true);

  // editor
  const editorRef = useRef<ReactQuill>(null);
  const [content, setContent] = useState(''); // only use for ReactQuill.initValue
  const [wordCount, setWordCount] = useState(0);

  // tilte
  const [title, setTitle] = useState<string>('第 章');

  // save-btn
  const [saving, setSaving] = useState(false);

  // publish-btn
  const [publishing, setPublishing] = useState(false);

  // undo-btn, redo-btn
  const [dis_undo, setDis_undo] = useState(true);
  const [dis_redo, setDis_redo] = useState(true);

  const loadNovelInfo = async () => {
    try {
      const resp = await getNovelInfoUsingGet({
        id: Number(novelId),
      });

      setNovelInfo(resp.data ?? {});

    } catch (error: any) {
      MessageError(error);
    }
  };

  const loadChapter = async () => {
    try {
      const resp = await getChapterByIdUsingGet({
        chapterId: Number(chapterId),
      })
      setChapter(resp.data ?? {});
    } catch (error) {
      MessageError(error);
    }
  };

  const loadText = async (url: string) => {
    if (!url) return;
    try {
      // setLoading(true);
      // TODO: attention: fetch
      const resp = await fetch(url);
      if (!resp.ok) {
        const error: any = new Error("get file error");
        error.name = 'respError';
        error.info = {
          code: resp.status,
          data: null,
          message: "get file error"
        };
        throw error;
      }
      const t = await resp.text();
      setContent(t);

    } catch (error) {
      MessageError(error);
      setContent('');
    } finally {
      // setLoading(false);
    }
  };

  useEffect(() => {
    loadNovelInfo();
  }, [novelId]);

  // loadChapter().then = () => setTitle() && loadText().then = () => quill?.setText(...);
  useEffect(() => {
    loadChapter();
  }, [chapterId]);

  useEffect(() => {
    setTitle(chapter.title ?? '');
  }, [chapter.title])

  useEffect(() => {
    loadText(chapter.res ?? '');
  }, [chapter.res])

  useEffect(() => {
    const quill = editorRef.current?.getEditor();
    if (quill) {
      quill.setText(content);
    }
  }, [content])

  // 计算字数
  const calculateWordCount = (html) => {
    // 去掉空格
    const text = html.replace(/\s/g, ''); // /<[^>]*>/g
    return text.length;
  };

  // 监听editor内容变化
  const handleTextChange = () => {
    const quill = editorRef.current?.getEditor();

    setWordCount(calculateWordCount(quill?.getText()));

    // 更新 undo-btn, redo-btn 状态
    const qhistory: any = quill?.history;
    setDis_undo(qhistory.stack?.undo.length <= 0);
    setDis_redo(qhistory.stack?.redo.length <= 0);

    // console.debug("stack: "+ JSON.stringify(qhistory.stack));
    // console.debug("undo: "+qhistory.stack?.undo.length);
    // console.debug("redo: "+qhistory.stack?.redo.length);
    // console.debug('----------------------');
  };

  // save-btn
  const handleSave = async () => {
    if(wordCount <= 0 || title.length <= 0) {
      message.info('标题或正文不能为空');
      return;
    }
    const quill = editorRef.current?.getEditor();
    const text_ = quill?.getText();
    try {
      setSaving(true);
      const resp = await saveChapterUsingPost({
        id: Number(chapterId),
        title: title,
        txt: text_,
      });

      if(resp.data ) {
        message.success('保存成功');
        quill?.history.cutoff();
      }
    } catch (error) {
      message.error('保存失败');
      MessageError(error);
    } finally {
      setSaving(false);
    }
  };

  // publish-btn
  const handleSubmit = async () => {
    // if(wordCount < 1000) {
    //   message.info('至少1000字才可以发布文章');
    //   return;
    // }
    try {
      setPublishing(true);
      const resp = await switchChapterStatusUsingPost({
        id: Number(chapterId),
        status: EnumChapterStatus.REVIEWING,
      });
      if(resp.data) {
        message.success('发布成功');
      }
      
    } catch (error) {
      message.error('发布失败');
      MessageError(error);
    } finally {
      setPublishing(false);
    }
  };

  // back-btn
  const handleBack = () => {
    history.push("/user/home",
      {
        initTab: "chapter-manage",
        novelId: novelId,
      }
    );
  };

  // undo-btn, redo-btn
  const handleUndo = () => {
    const quill = editorRef.current?.getEditor();
    if (quill) {
      quill.history.undo();
    }
  };

  const handleRedo = () => {
    const quill = editorRef.current?.getEditor();
    if (quill) {
      quill.history.redo();
    }
  };

  const handleFormat = () =>{
    const quill = editorRef.current?.getEditor();
    if(!quill) return;
    const delta = quill.getContents();
    // console.debug("delta:\n"+JSON.stringify(delta));
    
    const newDelta: any  = {
      ...delta,
      ops: delta.ops.map(op =>{
        if(op.insert && typeof op.insert === 'string') {
          op.insert = op.insert.replace(/\n{2,}/g, '\n');
        }
        return op;
      }),
    };
    quill.setContents(newDelta); // attention: miss type error

  };


  return (
    <Layout className="novel-publish-layout">
      <Header className="publish-header">
        <div className="header-content">
          <Button
            className="back-button"
            icon={<LeftOutlined />}
            type="text"
            onClick={() => handleBack()}
          >
          </Button>

          <h2>{novelInfo.name}</h2>

          <div className="action-buttons">
            <Button loading={saving} onClick={handleSave}>保存</Button>
            <Button type="primary" loading={publishing} onClick={handleSubmit}>
              发布
            </Button>
          </div>
        </div>
      </Header>
      <Layout className="content-layout">
        <Content className="publish-content">

          <Card className="editor-card">

            <Input
              className="title-input"
              variant="borderless"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder='请输入标题'
            />


            <ReactQuill
              // className={styles.custom_quill_editor}
              className="custom-quill-editor"
              ref={editorRef}
              onChange={() => handleTextChange()}
              formats={[]}
              modules={{
                toolbar: false,
                clipboard: {
                  matchVisual: false,
                },
                history: {
                  delay: 2000, // 2s记录一次操作历史
                  maxStack: 200, // 最大记录200次操作历史
                  userOnly: true,
                }
              }}
              placeholder="　      请输入正文" //全角空格

            />
            
          </Card>
        </Content>
      </Layout>
      <Footer className='publish-footer'>
        <div className="editor-footer">
          <span className='footer-word-counter'>
            字数: {wordCount}
          </span>
          <div className='footer-btns'>
            <Tooltip title={"撤消"}>
              <Button type={'text'} icon={<UndoOutlined />}
                disabled={dis_undo}
                onClick={() => handleUndo()}
              />
            </Tooltip>

            <Tooltip title={"重做"}>
              <Button className='not-first-btn' type={'text'} icon={<RedoOutlined />}
                disabled={dis_redo}
                onClick={() => handleRedo()}
              />
            </Tooltip>

            <Tooltip title={"格式化"}>
              <Button className='not-first-btn' type={'text'} icon={<AlignRightOutlined />}
                onClick={() => handleFormat()}
              />
            </Tooltip>
          </div>

        </div>
      </Footer>
    </Layout>
  );
};

export default WriterModify;